//
//  LRStatusPicCollectionV.swift
//  WeiboX
//
//  Created by admin on 06/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

private let itemMargin: CGFloat = 5
private let itemWidth = (ScreenWidth - 2 * StatusItemMargin - 2 * itemMargin) / 3

class LRStatusPicCollectionV: UICollectionView {
	
	fileprivate let statusPicCellID = "statusPicCellID"
	
	var selfSizeConstraint: Constraint?
	
	var picUrls: [LRStatusPicInfo]? {
		didSet {
			contentLabel.text = "\(picUrls?.count ?? 0)"
			
			calcItemSize(count: picUrls?.count ?? 0)
			
			reloadData()
		}
	}
	
	override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
		
		let flowLayout = UICollectionViewFlowLayout()
		
		flowLayout.itemSize = CGSize.init(width: itemWidth, height: itemWidth)
		flowLayout.minimumLineSpacing = itemMargin
		flowLayout.minimumInteritemSpacing = itemMargin
		
		super.init(frame: frame, collectionViewLayout: flowLayout)
		
		setupUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	fileprivate lazy var contentLabel: UILabel = {
		let label = UILabel(fontSize: 20, textColor: .blue)
		label.text = "9"
		return label
	}()
	
	private func calcItemSize(count: Int) {
		let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
		
		if count == 1 {
			if let imgUrl = picUrls!.first!.thumbnail_pic {
				if let img = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imgUrl) {
					
					//			let imgV = UIImageView()
					//			imgV.backgroundColor = .red
					var imgSize = img.size
					
					// 过窄处理
					if imgSize.width < 80 {
						let imgW: CGFloat = 80
						var imgH = imgW * imgSize.height / imgSize.width
						
						// 过长处理
						if imgH > 150 {
							imgH = 150
						}
						
						// 处理后的图片尺寸
						imgSize = CGSize(width: imgW, height: imgH)
					}
					
					selfSizeConstraint?.deactivate()
					self.snp.makeConstraints({ (make) in
						selfSizeConstraint = make.size.equalTo(imgSize).constraint
					})
					
					flowLayout.itemSize = imgSize
					
					self.layoutIfNeeded()
				}
			}
//			return
		} else {
			// 列数
			let cols =  count > 3 ? 3 : count
			// 行数
			let rows = (count + 2) / 3
			// 配图宽度
			let currentWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
			// 配图高度
			let currentHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
			
			let currentSize = CGSize(width: currentWidth, height: currentHeight)
			
			selfSizeConstraint?.deactivate()
			self.snp.makeConstraints({ (make) in
				selfSizeConstraint = make.size.equalTo(currentSize).constraint
			})
			
			
			
			flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
			
//			if count == 0{
//				return
//			}
//			
			self.layoutIfNeeded()
		}
	}
	
	
}

// MARK: - 设置 UI 界面
extension LRStatusPicCollectionV {
	fileprivate func setupUI() {
		register(LRStatusPicCollectionVCell.self, forCellWithReuseIdentifier: statusPicCellID)
		
		backgroundColor = .white
		dataSource = self
		
		addSubview(contentLabel)
		
		contentLabel.snp.makeConstraints { (make) in
			make.center.equalToSuperview()
		}
	}
}

// MARK: - 数据源方法
extension LRStatusPicCollectionV: UICollectionViewDataSource {
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
		
		return picUrls?.count ?? 0
	}
	
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
		let cell: LRStatusPicCollectionVCell = dequeueReusableCell(withReuseIdentifier: statusPicCellID, for: indexPath) as! LRStatusPicCollectionVCell
		
		cell.backgroundColor = .red
		
		cell.picInfo = picUrls![indexPath.item]
		
		return cell
	}
}

// MARK: - 自定义 cell
class LRStatusPicCollectionVCell: UICollectionViewCell {
	var picInfo: LRStatusPicInfo? {
		didSet {
			if let picUrl = picInfo?.thumbnail_pic {
				imgView.sd_setImage(with: URL(string: picUrl), placeholderImage: #imageLiteral(resourceName: "timeline_image_placeholder"))
			}
		}
	}
	
	lazy var imgView: UIImageView = {
		let imgV = UIImageView(image: #imageLiteral(resourceName: "timeline_image_placeholder"))
		// 设置图片原始比例显示
		imgV.contentMode = .scaleAspectFill
		// 剪切掉多余的部分
		imgV.clipsToBounds = true
		return imgV
	}()
	
	override init(frame: CGRect) {
		super.init(frame: frame)
		setupUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setupUI() {
		contentView.addSubview(imgView)
		
		imgView.snp.makeConstraints { (make) in
			make.edges.equalToSuperview()
		}
	}
}
